package cn.easy.mortgage.service;

import cn.easy.base.SpringContext;
import cn.easy.base.domain.Area;
import cn.easy.base.service.AreaService;
import cn.easy.mortgage.bean.SelectBean;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springside.modules.utils.collection.ListUtil;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import static cn.easy.mortgage.utils.Constants.AREA_EXCLUDE;

@Component
public class CommonService {

    @Cacheable(value = "getAreaList")
    public List<SelectBean> getAreaList() {
        String queryCode = "";
        String parentCode = "330100";
        String codeType = "area";
        if (StringUtils.isNotBlank(codeType)) {
            if ("province".equals(codeType)) {
                queryCode = "%0000";
            } else if ("city".equals(codeType)) {
                queryCode = StringUtils.isNotEmpty(parentCode) ? parentCode.substring(0, 2) + "%" + "00" : queryCode;
            } else {
                queryCode = StringUtils.isNotEmpty(parentCode) ? parentCode.substring(0, 4) + "%" : queryCode;
            }
        }
        AreaService areaService = SpringContext.getBean(AreaService.class);
        List<Area> areaList = areaService.findChildrenAreas(queryCode, codeType);
        List<SelectBean> list = new ArrayList();
        if (!areaList.isEmpty()) {
            Iterator var7 = areaList.iterator();

            while (var7.hasNext()) {
                Area area = (Area) var7.next();
                if (StringUtils.equalsAny(area.getCode(), AREA_EXCLUDE)) {
                    continue;
                }
                list.add(new SelectBean(area.getName(), area.getCode()));
            }
        }

        ListUtil.sort(list, new Comparator<SelectBean>() {
            public int compare(SelectBean o1, SelectBean o2) {
                try {
                    return PinyinHelper.getShortPinyin(o1.getValue()).compareTo(PinyinHelper.getShortPinyin(o2.getValue()));
                } catch (PinyinException var4) {
                    var4.printStackTrace();
                    return 0;
                }
            }
        });

        return list;
    }

}
